package com.fengqianrun.bootframework.config;

import cn.hutool.core.util.StrUtil;
import com.aizuda.easy.security.code.BasicCode;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.exp.impl.BasicException;
import com.fengqianrun.bootframework.config.i18n.MessageHelperConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
@Slf4j
@RestControllerAdvice
@RestController
public class GlobalExceptionConfig {

    /**
     * 处理Exception异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Rep handleAllExceptions(Exception e, WebRequest request) {
        if (e instanceof NoHandlerFoundException) {
            Integer code = BasicCode.BASIC_CODE_404.getCode();
            return Rep.error(code,MessageHelperConfig.getMessage(code));
        }
        if(e instanceof BasicException){
            BasicException cause = (BasicException) e;
            return Rep.error(cause.getCode(),MessageHelperConfig.getMessage(cause.getCode()));
        }
        if(e.getCause() instanceof BasicException){
            BasicException cause = (BasicException) e.getCause();
            return Rep.error(cause.getCode(),MessageHelperConfig.getMessage(cause.getCode()));
        }
        if(e instanceof IllegalArgumentException){
            Integer code = BasicCode.BASIC_CODE_99999.getCode();
            return Rep.error(code,MessageHelperConfig.getMessage(code));
        }
        if(e instanceof MissingServletRequestParameterException){
            Integer code = BasicCode.BASIC_CODE_99998.getCode();
            return Rep.error(code,MessageHelperConfig.getMessage(code));
        }
        if(e instanceof HttpRequestMethodNotSupportedException){
            String msg = e.getMessage();
            Integer code = BasicCode.BASIC_CODE_99997.getCode();
            msg = MessageHelperConfig.getMessage(code) +
                    (StrUtil.isEmpty(msg) ? "": msg.substring(msg.indexOf("'")-1, msg.lastIndexOf("'")+1));
            return Rep.error(BasicCode.BASIC_CODE_99997.getCode(),msg);
        }
        e.printStackTrace();
        String msg =  MessageHelperConfig.getMessage(BasicCode.BASIC_CODE_500.getCode());
        return Rep.error(BasicCode.BASIC_CODE_500.getCode(), msg);
    }

    @RequestMapping("/failure/authenticationFilter")
    public Rep error(@RequestParam("code") Integer code, @RequestParam("msg") String msg) {
        return Rep.error(code, MessageHelperConfig.getMessage(code));
    }

}
